define(function (require, exports, module) {

    require("apps/grid");
    require("apps/easyui");

    exports.init = function (ctx, uuid) {
        var _pageComponent = new $.PageDomFactory(uuid);
        var pageListComponent = new $.PageListComponent(uuid, {
            view: {
                grid: "grid",
                myToolbar: "nsdb",
                colbar: "document_tempate"
            },
            configs: {
                gridUrl: ctx + '/app/api/document/allList',
                gridColumns: [
                    {
                        field: 'id',
                        checkbox: true
                    },
                    {
                        field: 'temp1',
                        hidden: true
                    },
                    {
                        field: 'docNow.docName',
                        title: '名称',
                        width: 100,
                        align: 'left'

                    },
                    {
                        field: 'docNow.moduleType.dirValue',
                        title: '类型',
                        width: 50,
                        align: 'left'
                    },
                    {
                        field: 'docNow.docKeyWord',
                        title: '关键字',
                        width: 100,
                        align: 'left'

                    },
                    {
                        field: 'docNow.createUser.userName',
                        title: '创建用户',
                        width: 50,
                        align: 'left'
                    },
                    {
                        field: 'docNow.createTime',
                        title: '创建日期',
                        width: 60,
                        align: 'left'
                    },
                    {
                        field: 'docNow.docBelong.orgName',
                        title: '所属部门',
                        width: 100,
                        align: 'left'
                    },
                    {
                        field: 'docNow.docStatus',
                        title: '状态',
                        width: 50,
                        align: 'left',
                        formatter: function (value, row, index) {
                            return value == "DOC_STATUS_PUBLISHED" ? "已发布" : "未发布";
                        }
                    },
                    {
                        field: 'docNow.version',
                        title: '版本',
                        width: 50,
                        align: 'left',
                        formatter: function (value, row, index) {
                            return "V" + value;
                        }
                    }
                ]
            },
            events: {
                renderColBarBefore: function (type, row) {
                    if (type == "publish") {
                        return row.docNow.docStatus == "DOC_STATUS_UN_PUBLISHED"
                    }
                    return true;
                },
                onClickColBtn: function (context, btn, row) {
                    switch (btn.key) {
                        case "edit":
                            whenEdit(context, btn.href, row.id);
                            break;
                        case "range":
                            whenSetRange(context, btn.href, row);
                            break;
                        case "publish":
                            whenPublish(context, btn.href, row);
                            break;
//                    case "view":
//                        context.detail('文档详情',row);
//                        break;
                        default :
                            break;
                    }
                },
                onClickToolbarBtn: function (context, btn) {
                    switch (btn.key) {
                        case "search_all":
                            context.searchAll();
                            break;
                        case "search":
                            context.search(btn.href, "文库搜索", "document_search");
                            break;
                        case "add":
                            whenAdd(context, btn.href);
                            break;
                        case "del":
                            whenDel(context, btn.href);
                            break;
                        default :
                            break;
                    }
                }
            }
        });

        var contextWindow = new $.PageWindow();

        function whenAdd(context, href) {
            contextWindow.create({
                href: href,
                method: "document_add_save",
                title: "新增文档",
                callback: function (status) {
                    if (status) {
                        context.grid.datagrid("reload");
                    }
                }
            });
            contextWindow.open();
        }

        function whenDel(context, href) {
            var rows = context.grid.datagrid('getChecked');
            if (rows.length == 0) {
                $.messager.alert('信息', '请先选择一行', 'info');
                context.grid.datagrid('clearSelections');
                return;
            }
            for (var i = 0; i < rows.length; i++) {
                if (rows[i].docNow.docStatus == "DOC_STATUS_PUBLISHED") {
                    $.messager.alert('信息', '已发布的不能删除', 'info');
                    return;
                }
            }
            if (rows.length > 0) {
                $.messager.confirm('确定', '确定要删除吗?', function (result) {
                    if (result) {
                        var ids = [];
                        for (var i = 0; i < rows.length; i++) {
                            ids.push(rows[i].id);
                        }
                        $.post(
                            href,
                            $.utils.buildJson({ids: ids}),
                            function (json) {
                                if ($.isErrorRequest(json)) {
                                    $.messager.alert('信息', json.msg, 'info');
                                } else {
                                    $.messager.alert('信息', '删除成功', 'info');
                                    context.grid.datagrid("reload");
                                }
                            }
                        );
                    }
                });
            }
        }

        function whenEdit(context, href, id) {
            contextWindow.create({
                href: href + "?id=" + id,
                method: "document_edit_save",
                title: "编辑文档",
                callback: function (status) {
                    if (status) {
                        context.grid.datagrid("reload");
                    }
                }
            });
            contextWindow.open();
        }

        function whenSetRange(context, href, row) {
            contextWindow.create({
                href: href + "?id=" + row.id + "&&publish=false",
                method: "document_range_save",
                title: "设置文档'" + row.docNow.docName + "'访问权限",
                callback: function (status) {
                    if (status) {
                        context.grid.datagrid("reload");
                    }
                }
            });
            contextWindow.open();
        }

        function whenPublish(context, href, row) {
            if (row.docRangeType == null) {
                $.messager.defaults = {ok: '设置', cancel: '取消'};
                $.messager.confirm('操作提示', '请先设置访问权限再发布', function (result) {
                    if (result) {
                        contextWindow.create({
                            href: ctx + "/app/api/document/toRange?id=" + row.id + "&&publish=true",
                            method: "document_range_save",
                            title: "设置文档'" + row.docNow.docName + "'访问权限",
                            callback: function (status) {
                                if (status) {
                                    context.grid.datagrid("reload");
                                }
                            }
                        });
                        contextWindow.open();
                    }
                });
                $.messager.defaults = {ok: '确定', cancel: '取消'};
            } else {
                $.post(href + "?id=" + row.id, function (json) {
                    if ($.isErrorRequest(json)) {
                        $.messager.alert('信息', json.msg, 'info');
                    } else {
                        $.messager.alert('信息', '发布成功', 'info');
                    }
                    context.grid.datagrid("reload");
                });
            }
        }
    };

    require("apps/file");
    require("apps/tag");
    exports.add = function (ctx, uuid) {
        var page = new $.PageDomFactory(uuid, true);

        page.getJqDom("moduleType").combobox({
            loadFilter: function (data) {
                return data.content;
            },
            url: WE.contextPath + "/app/api/directory/list?dirGroup=DIRECTORY_DOCUMENT_TYPE",
            valueField: 'id',
            textField: 'dirValue',
            editable: false
        });

        page.getJqDom("docBelong").combobox({
            url: ctx + '/app/api/organization/findAll',
            valueField: 'id',
            textField: 'orgName',
            editable: false
        });

        page.getJqDom("uploadCover").fileupload({
            'uploader': ctx + '/app/api/file/uploadTempFile',
            onUploadSuccess: function (files) {
                var file = files[0];
                page.getJqDom("fileMessage").show().html(file.fileHtml);
                page.getJqDom("fileMessage").children().children().css({border: "none"});
                page.getJqDom("attachmentName").val(file.name);
            }
        });

        page.getJqDom("docKeyWord").tagEditor({
            delimiter: ',',
            clickDelete: true,
            maxLength: 5,
            placeholder: '关键字..'
        });

        window.document_add_save = function (win) {
            if (!page.getJqDom('form-document-add-info').form('validate')) {
                return false;
            }
            var form = page.getJqDom("form-document-add-info");
            var postData = form.serializeJson();
            if (!postData.docKeyWord) {
                $.messager.alert('信息',
                    "至少需要填写一个关键字", 'info');
                return;
            }
            if (postData.docKeyWord.split(",").length > 5) {
                $.messager.alert('信息',
                    "最多只能添加五个关键字", 'info');
                return;
            }
            if (!postData.attachment) {
                $.messager.alert('信息',
                    "至少需要上传一个文档资料", 'info');
                return;
            }
            win.wait("start", "保存中,请稍候.");
            $.post(form.attr("action")
                    + "?random=" + Math.random(), $.utils.buildJson(postData),
                function (json) {
                    win.wait("end");
                    if ($.utils.isError(json)) {
                        $.messager.alert('信息',
                            json.msg, 'info');
                        win.callback(false);
                    } else {
                        $.messager.alert('信息',
                            '保存成功', 'info');
                        win.callback(true);
                        win.close();
                    }
                }, "json");

        }
    };

    exports.update = function (ctx, uuid, config) {
        var page = new $.PageDomFactory(uuid, true);

        page.getJqDom("moduleType").combobox({
            loadFilter: function (data) {
                return data.content;
            },
            url: WE.contextPath + "/app/api/directory/list?dirGroup=DIRECTORY_DOCUMENT_TYPE",
            valueField: 'id',
            textField: 'dirValue',
            value: config.versionId,
            editable: false
        });

        page.getJqDom("docBelong").combobox({
            url: ctx + '/app/api/organization/findAll',
            valueField: 'id',
            textField: 'orgName',
            value: config.belongId,
            editable: false
        });

        page.getJqDom("uploadCover").fileupload({
            'uploader': ctx + '/app/api/file/uploadTempFile',
            onUploadSuccess: function (files) {
                var file = files[0];
                page.getJqDom("fileMessage").show().html(file.fileHtml);
                page.getJqDom("fileMessage").children().children().css({border: "none"});
                page.getJqDom("attachmentName").val(file.name);
            }
        });

        page.getJqDom("docKeyWord").tagEditor({
            delimiter: ',',
            clickDelete: true,
            maxLength: 5,
            placeholder: '关键字..'
        });

        window.document_edit_save = function (win) {
            if (!page.getJqDom('form-document-edit-info').form('validate')) {
                return false;
            }
            var form = page.getJqDom("form-document-edit-info");
            var postData = form.serializeJson();
            if (!postData.docKeyWord) {
                $.messager.alert('信息',
                    "至少需要填写一个关键字", 'info');
                return;
            }
            if (postData.docKeyWord.split(",").length > 5) {
                $.messager.alert('信息',
                    "最多只能添加五个关键字", 'info');
                return;
            }
            win.wait("start", "保存中,请稍候.");
            $.post(form.attr("action")
                    + "?random=" + Math.random(), $.utils.buildJson(postData),
                function (json) {
                    win.wait("end");
                    if ($.isPlainObject(json) && json.error) {
                        $.messager.alert('信息',
                            json.msg, 'info');
                        win.callback(false);
                    } else {
                        $.messager.alert('信息',
                            '保存成功', 'info');
                        win.callback(true);
                        win.close();
                    }
                }, "json");

        }
    };

    exports.search = function (ctx, uuid) {
        var page = new $.PageDomFactory(uuid, true);

        page.getJqDom("moduleType").combobox({
            loadFilter: function (data) {
                return data.content;
            },
            url: WE.contextPath + "/app/api/directory/list?dirGroup=DIRECTORY_DOCUMENT_TYPE",
            valueField: 'id',
            textField: 'dirValue',
            editable: false
        });

        page.getJqDom("docBelong").combobox({
            url: ctx + '/app/api/organization/findAll',
            valueField: 'id',
            textField: 'orgName',
            editable: false
        });

        page.getJqDom("docKeyWord").tagEditor({
            delimiter: ',',
            clickDelete: true,
            maxLength: 5,
            placeholder: '关键字..'
        });

        window.document_search = function (win) {
            win.wait("start", "搜索中，请稍候！");
            var form = page.getJqDom("form-document-search-info");
            var postData = form.serializeJson();
            win.callback(postData);
            win.close();
        }
    };

    require("apps/boxselect");
    exports.range = function (ctx, uuid, config) {
        var page = new $.PageDomFactory(uuid);
        page.getJqDom("postForm").find("input:radio").click(function () {
            if ($(this).val() == 3) {
                page.getJqDom("selectUser").show();
            } else {
                page.getJqDom("selectUser").hide();
            }
        });
        page.getJqDom("doc_users").mutiSelect({
            url: ctx + "/app/api/sysMember/list",
            idFiled: "id",
            textFiled: "userDescription"
        });

        window.document_range_save = function (win) {
            win.wait("start", "保存中,请稍候.");
            var postData = page.getJqDom("postForm").serializeJson();
            $.post(ctx + "/app/api/document/saveRange", $.utils.buildJson(postData), function (json) {
                win.wait("end");
                if (config.publish()) {
                    $.post(ctx + "/app/api/document/publish?id=" + config.copyId, function (json) {
                        if ($.isErrorRequest(json)) {
                            $.messager.alert('信息', json.msg, 'info');
                        } else {
                            $.messager.alert('信息', '发布成功', 'info');
                            win.callback(true);
                        }
                    });
                } else {
                    $.messager.alert('信息', '保存成功!', 'info');
                }
                win.callback(true);
                win.close();
            }, 'json');
        }
    }
});